﻿using sinetd.Utilities;

namespace sinetd.Services.Ping
{
    public class Service : BaseService, IService
    {
        public Service() : base("Ping") { }

        #region IService Members

        public void HandleNewConnection(IConnectionIO conn)
        {
            bool handled = false;

            string msg = conn.Recv();
            if (msg != null)
            {
                msg = msg.Trim();

                string[] parts = msg.Split(' ');

                if (parts[0].ToLower() == "ping")
                {
                    int length = 0;
                    if (int.TryParse(parts[1], out length))
                    {
                        conn.Send(this.Pong(length));
                        handled = true;
                    }
                }
            }

            if (!handled)
            {
                conn.Send("gong");
            }
        }

        public void Shutdown()
        {
        }

        #endregion

        public string Ping(int size, string data = null)
        {
            return "ping " + size + (data != null ? " " + data : "");
        }

        protected string Pong(int size)
        {
            return "pong " + Misc.RandomString(size);
        }
    }
}
